#pragma once
#include <functional>
#include "Socket.h"        // 封装套接字操作
#include "InetAddress.h"   // 封装IP和端口
#include "Channel.h"      // 管理I/O事件回调
#include "EventLoop.h"     // 事件循环核心
#include"Buffer.h"
#include <memory>
#include <atomic>
class Connection:public std::enable_shared_from_this<Connection>
{
private:
    EventLoop *loop_;       // 事件循环指针（由外部传入）
    //Socket *clientsock_;      // 服务端监听Socket（内部创建）
    std::unique_ptr<Socket> clientsock_;
    // Channel *clientchannel_;// 监听Socket对应的Channel（绑定读事件回调）
    std::unique_ptr<Channel> clientchannel_;
    std::function<void(std::shared_ptr<Connection>)> closecallback_;
    std::function<void(std::shared_ptr<Connection>)> errorcallback_;

    // 处理数据的回调函数
    std::function<void(std::shared_ptr<Connection>,std::string&)> haddlemsgcallback_;

    std::function<void(std::shared_ptr<Connection>)> sendcompletecallback_;

    Buffer inputbuffer_;
    Buffer outputbuffer_;
    std::atomic_bool disconnect_;
public:
    Connection(EventLoop *loop,std::unique_ptr<Socket> clientsock);
    ~Connection();

    std::string ip();
    uint16_t port();

    int fd() const;         // 返回文件描述符

    void closecallback();
    void errorcallback();

    void setclosecallback(std::function<void(std::shared_ptr<Connection>)> f);
    void seterrorcallback(std::function<void(std::shared_ptr<Connection>)> f);

    void sethaddlemsgcallback(std::function<void(std::shared_ptr<Connection>,std::string&)> f);

    void setsendcompletecallback(std::function<void(std::shared_ptr<Connection>)> f);

    void onmessage();

    void send(const char*data,int size );

    void sendinloop(const char*data,int size );

    void sendcallback();
};  